package com.mis.pos.repository;

import com.mis.pos.dto.ItemNumberDTO;
import com.mis.pos.entity.ItemEntity;
import com.mis.pos.entity.SaleItemEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @Description 订单实体关联DAO
 * @Author yuxiang
 * @CreatedDate 2019/11/17 19:27
 */
@Repository
public interface SaleItemRepository extends JpaRepository<SaleItemEntity,Long>, JpaSpecificationExecutor<SaleItemEntity> {

    /**
     * 保存全部订单关联实体
     * @param iterable
     * @param <S>
     * @return
     */
    @Override
    <S extends SaleItemEntity> List<S> saveAll(Iterable<S> iterable);

    /**
     * 根据订单Id查询全部商品Id
     * sql:
     *  SELECT	it.`id`, it.`item_name`,si.`item_number` FROM item it LEFT JOIN sale_item si ON (it.`id` = si.item_id) WHERE si.`sale_id`=1
     * @param saleId
     * @return
     */
    @Query(value = "select new com.mis.pos.dto.ItemNumberDTO(it.id,it.itemName,si.itemNumber) from ItemEntity it left join SaleItemEntity si on (" +
            "it.id = si.itemId ) where si.saleId= :saleId")
//    @Query(value = "SELECT it.`id`, it.`item_name`,si.`item_number` FROM item it LEFT JOIN sale_item si ON (it.`id` = si.item_id) WHERE si.`sale_id`=?1",nativeQuery = true)
    List<ItemNumberDTO> searchItemIdsBySaleId(@Param("saleId") Long saleId);

    /**
     * 根据订单id查询全部订单商品关联记录
     * @param saleId
     * @return
     */
    List<SaleItemEntity> findSaleItemEntitiesBySaleId(Long saleId);

    /**
     * 根据订单id删除订单商品关联记录
     * @param saleId
     * @return
     */
    @Transactional
    @Modifying
    int deleteSaleItemEntitiesBySaleId(Long saleId);
}
